import {
	apiBaseURL
} from '@/utils/config'
import store from '@/store/index'
import {
	getToken
} from '@/utils/auth.js'

// 封装微信请求
export function request(method, url, data, showLoading = false) {
	return new Promise((resolve, reject) => {
		let c = {
			data: data,
			method: method,
			url: apiBaseURL + url,
			timeout: 3000,
			header: {
				'content-type': 'application/json'
			},
			success: function(res) {
				if (res.statusCode == 200) {
					// 正确
					if (res.data.code == 20000) {
						resolve(res.data.data)
					}
					// 登录超时,Token失效
					else if (res.data.code == 50008) {
						reject('登录超时')
					}
					// 错误
					else {
						reject(res.data.msg)
					}

				} else
					reject("网络请求失败,请重试!")
			},
			fail: function(err) {
				reject(err.errMsg)
			},
			complete: function() {
				if (showLoading === true)
					uni.hideLoading()
			}
		}
		if (showLoading === true) {
			uni.showLoading({
				title: "加载中",
				mask: true,
			})
		}

		if (store.state.token)
			c.header['X-Token'] = getToken()

		uni.request(c)
	})
}